require 'coffee-script/register'
fs = require('fs')
{spawn, exec} = require 'child_process'

run = (args, cb) ->
  proc =         spawn 'coffee.cmd', args
  proc.stderr.on 'data', (buffer) -> console.log buffer.toString()
  proc.on        'exit', (status) ->
    process.exit(1) if status != 0
    cb() if typeof cb is 'function'

build = (cb) ->
  files = fs.readdirSync 'src'
  files = ('src/' + file for file in files when file.match(/\.coffee$/))
  run ['-c', '-o', 'lib'].concat(files), cb

task 'build', 'Run full build', ->
  invoke 'build:compile'
  invoke 'build:parser'
  setTimeout (-> invoke 'build:browser'), 100

task 'build:compile', 'Compile all coffee files to js', 
  build
    
task 'build:parser', 'rebuild the SQL parser', ->
  parser = require('./src/grammar.coffee').parser
  fs.writeFileSync 'lib/compiled_parser.js', parser.generate()

task 'build:browser', 'Build a single JS file suitable for use in the browser', ->
  code = ''
  for name in ['lexer', 'compiled_parser', 'nodes', 'parser', 'sql_parser']
    code += """
      require['./#{name}'] = new function() {
        var exports = this;
        #{fs.readFileSync "lib/#{name}.js"}
      };
    """
  _code = code
  
  code = """
(function(root) {
var SQLParser = function() {
  function require(path){ return require[path]; }
  #{code}
   return require['./sql_parser']
}();

if(typeof define === 'function' && define.amd) {
 define(function() { return SQLParser });
} else { root.SQLParser = SQLParser }
}(this));
   """
  fs.writeFileSync './browser/sql-parser.js', code
  
  
  code = """
/*!
#{fs.readFileSync "LICENSE.txt"}

-----------
SQL Parser

SQL Parser is a lexer, grammar and parser for SQL written in JS.
Currently it is only capable of parsing fairly basic SELECT queries but full SQL support will hopefully come in time.
See the specs for examples of currently supported queries.
*/
(function(factory, context, baseLibId){

    var deps = [baseLibId]
         ,i, len, dep = '', missing = [];

    for(i = 0, len = deps.length; i  < len; i++){
        dep = deps[i];
        if( undefined === context[dep] ){
            missing = missing.concat([dep]);
        }            
    }
    
    if( missing.length > 0 ){
    
        if( typeof define === 'function' && define.amd ){
            
            define(missing, function(){
                var baseLib = context[baseLibId];
                factory(baseLib);                
                return baseLib.sqlParser;                
            });
            
            return;
        }
        
        throw new Error('re_sqlparser requires the following libraries: ' + missing.join(','));
        
    }
    
    factory(context[baseLibId]);
    
}(function(baseLib){

baseLib.sqlParser = function() {
    function require(path){ return require[path]; }
    #{_code}
    return require['./sql_parser']
}();

if(typeof define === 'function' && define.amd) {
    define('re_sqlparser', [], function() {
        return baseLib.sqlParser;
    });
}

}, this, 're'));
   """  
  fs.writeFileSync '../standard/re.sqlparser.js', code